package top.lyc829.mymusic.ui.fragment.music_player

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.media.session.PlaybackState
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.animation.LinearInterpolator
import android.widget.SeekBar
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.TimeUtils
import com.lxj.xpopup.XPopup
import com.lzx.starrysky.OnPlayProgressListener
import com.lzx.starrysky.StarrySky
import com.lzx.starrysky.control.RepeatMode
import com.lzx.starrysky.manager.PlaybackStage
import top.lyc829.mymusic.R
import top.lyc829.mymusic.base.BaseFragment
import top.lyc829.mymusic.databinding.FragmentMusicPlayerBinding
import top.lyc829.mymusic.ext.loadWithBlur
import top.lyc829.mymusic.ui.custom.MusicListDialog
import top.lyc829.mymusic.util.DateUtils

class MusicPlayerFragment : BaseFragment<MusicPlayerViewModel, FragmentMusicPlayerBinding>() {

    companion object {
        fun newInstance() = MusicPlayerFragment()
        const val TAG = "MusicPlayerFragment"
    }

    private lateinit var mNeddlePlayAnimator: ObjectAnimator
    private lateinit var mNeddlePauseAnimator: ObjectAnimator

    override fun getViewModel() = ViewModelProvider(this).get(MusicPlayerViewModel::class.java)

    override fun getBinding(inflater: LayoutInflater) = FragmentMusicPlayerBinding.inflate(inflater)

    override fun initView(savedInstanceState: Bundle?) {
        initAnimator()
        binding.needle.rotation = 0f
    }

    override fun initClickListener() {
        binding.backView.setOnClickListener {
            findNavController().popBackStack()
        }

        //seekBar 可拖动
        binding.progressView.isEnabled = true
        binding.progressView.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                StarrySky.with().seekTo(seekBar?.progress?.toLong() ?:0, true)
            }
        })

        binding.playView.setOnClickListener {
            if (StarrySky.with().isPlaying()) {
                StarrySky.with().pauseMusic()
            } else if (StarrySky.with().isPaused()) {
                StarrySky.with().restoreMusic()
            }
        }

        binding.nextView.setOnClickListener {
            StarrySky.with().skipToNext()
        }

        binding.previousView.setOnClickListener {
            StarrySky.with().skipToPrevious()
        }

        binding.showListView.setOnClickListener {
            if (StarrySky.with().getPlayList().isEmpty()) {
                Toast.makeText(context, "当前播放队列没有歌曲", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            context?.let { c->
                XPopup.Builder(c)
                    .asCustom(MusicListDialog(c))
                    .show()
            }
        }

        binding.playModeView.setOnClickListener {
            eventViewModel.updateRepeatMode()
        }

    }

    override fun createObserver() {
        eventViewModel.playBackStage.observe(this) {
            when (it.stage) {
                PlaybackStage.PLAYING -> {
                    showPlayAnimator()
                    binding.playView.setImageResource(R.mipmap.audio_aj6)
                }
                PlaybackStage.PAUSE -> {
                    showPauseAnimator()
                    binding.playView.setImageResource(R.mipmap.audio_aj7)
                }
                else -> {
                    binding.needle.rotation = 0f
                    binding.playView.setImageResource(R.mipmap.audio_aj7)
                }
            }
            it.songInfo?.let { song ->

                binding.imgBackground.loadWithBlur(song.songCover, 300)

                binding.albumView.text = song.songName
                binding.authorView.text = song.artist
                binding.totalTimeView.text = DateUtils.formatMusicTime(song.duration)
                binding.progressView.max = song.duration.toInt()
            }
        }

        //观察播放进度
        StarrySky.with().setOnPlayProgressListener(object : OnPlayProgressListener {
            override fun onPlayProgress(currPos: Long, duration: Long) {
                binding.startTimeView.text = DateUtils.formatMusicTime(currPos)
                binding.progressView.progress = currPos.toInt()
            }
        })

        eventViewModel.repeatMode.observe(this) {
            when (it.repeatMode) {
                RepeatMode.REPEAT_MODE_NONE -> binding.playModeView.setImageResource(R.mipmap.ic_player_loop)
                RepeatMode.REPEAT_MODE_ONE -> binding.playModeView.setImageResource(R.mipmap.ic_player_once)
                RepeatMode.REPEAT_MODE_SHUFFLE -> binding.playModeView.setImageResource(R.mipmap.ic_player_random)
                RepeatMode.REPEAT_MODE_REVERSE -> binding.playModeView.setImageResource(R.mipmap.ic_player_loop)
                else -> binding.playModeView.setImageResource(R.mipmap.ic_player_loop)
            }
        }

    }

    override fun initData() {
    }

    private fun initAnimator() {
        //播放动作 动画
        mNeddlePlayAnimator = ObjectAnimator.ofFloat(binding.needle, "rotation", -25f, 0f)
        mNeddlePlayAnimator.duration = 200
        mNeddlePlayAnimator.repeatMode = ValueAnimator.REVERSE
        mNeddlePlayAnimator.repeatCount = 0
        mNeddlePlayAnimator.interpolator = LinearInterpolator()
        //暂停播放动作 动画
        mNeddlePauseAnimator = ObjectAnimator.ofFloat(binding.needle, "rotation", 0f, -25f)
        mNeddlePauseAnimator.duration = 200
        mNeddlePauseAnimator.repeatMode = ValueAnimator.REVERSE
        mNeddlePauseAnimator.repeatCount = 0
        mNeddlePauseAnimator.interpolator = LinearInterpolator()
    }

    private fun showPlayAnimator() {
        //唱针当前角度mNeddleiew.getRotation() : -25.0
        if (binding.needle.rotation.toDouble() == -25.0) {
            if (mNeddlePlayAnimator.isPaused) {
                mNeddlePlayAnimator.resume()
            } else {
                mNeddlePlayAnimator.start()
            }
        } else {
            Log.e(TAG, "showPlayAnimator() 唱针状态不正常")
        }
    }

    private fun showPauseAnimator() {
        //唱针当前角度mNeddleiew.getRotation() : 0
        if (binding.needle.rotation == 0f) {
            mNeddlePauseAnimator.start()
        } else {
            Log.e(TAG, "showPauseAnimator() 唱针状态不正常")
        }
    }


}